package com.sjp.myspring.web.servlet;

import com.sun.istack.internal.Nullable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JPView {

    public final static String DEFAULT_CONTENT_TYPE = "text/html;charset=utf-8";
    private File viewFile;

    public JPView(File viewFile) {
        this.viewFile = viewFile;
    }

    public void render(@Nullable Map<String, ?> model,
                       HttpServletRequest req, HttpServletResponse resp) throws Exception {
        StringBuilder sb = new StringBuilder();

        RandomAccessFile ra = new RandomAccessFile(this.viewFile, "r");
        String line = null;
        while (null != (line = ra.readLine())) {
            line = new String(line.getBytes("ISO-8859-1"), "utf-8");
            Pattern pattern = Pattern.compile("\\$\\{[^\\}]+\\}", Pattern.CASE_INSENSITIVE);//逐个匹配
            Matcher matcher = pattern.matcher(line);
            while (matcher.find()) {
                String paramName = matcher.group();
                paramName = paramName.replaceAll("\\$\\{|\\}", "");
                Object val = model.get(paramName);
                String value = val == null ? "" : val.toString();
                line = matcher.replaceFirst(value);

            }
            sb.append(line);
        }
        resp.setCharacterEncoding("utf-8");
        //resp.setContentType(DEFAULT_CONTENT_TYPE);
        resp.getWriter().write(sb.toString());
    }

}
